import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/constant/EcyEventConsnt.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyLogger.dart';
import 'package:ecy_app_flutter/ecycommon/utils/EcyUserUtil.dart';
import 'package:ecy_app_flutter/user/model/EcyUserModel.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../ecycommon/EcyAPI.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonPage.dart';
import '../../model/EcyApiCommonResponse.dart';
import 'model/EcyMyOrder.dart';

class EcyMyPage extends StatefulWidget {
  late _EcyMyPageViewState state;

  EcyMyPage();
  @override
  State<StatefulWidget> createState() {
    state = _EcyMyPageViewState();
    return state;
  }

  reloadData() {
    state.reloadData();
  }

  reloadOrderData() {
    state.reloadOrderData();
  }
}

final List<String> titleList = <String>['收货地址', '购物车', '消息', '我的动态','联系客服'];
final Map<int, String> routeMap = {
  0: EcyRouter.addressPage,
  1: EcyRouter.goodsCartHomePage,
  2: EcyRouter.myMessagePage,
  3: EcyRouter.myGroupMainPage,
  4: EcyRouter.contactUsPage
};

void handleOrderTap(BuildContext context, int index) {
  EcyRouter.pushWithNeedLogin(context, EcyRouter.myOrderPage, {
    EcyRouter.kTargetUrl: EcyRouter.myOrderPage,
    EcyRouter.kTargetParam: index > 3 ? index + 1 : index
  });
}

void handleConsignmentTap(BuildContext context, int index) {
  String url = index == 0
      ? EcyRouter.myConsignmentPublishListPage
      : index == 1
          ? EcyRouter.mySellListPage
          : EcyRouter.myBuyListPage;
  EcyRouter.pushWithNeedLogin(
      context, url, {EcyRouter.kTargetUrl: url, EcyRouter.kTargetParam: index});
}

class _EcyMyPageViewState extends State<EcyMyPage> {
  late EcyCommonBaseWidget controller;

  _EcyMyPageViewState();

  EcyUserModel _user = EcyUserModel("");
  int _unreadCount = 0;
  int _userLevel = -1;

  final List<String> _orderStatusList = [
    "拼团中",
    "待付款",
    "待发货",
    "待收货",
    "待评价",
    "售后"
  ];

  final List<int> _orderNumList = [0, 0, 0, 0, 0, 0];

  final List<String> _orderStatusImageList = [
    "assets/images/mine/grouping.png",
    "assets/images/mine/toBePayed.png",
    "assets/images/mine/toBeSent.png",
    "assets/images/mine/toBeReceived.png",
    "assets/images/mine/toBeCommented.png",
    "assets/images/mine/afterSale.png"
  ];
  final List<String> _consignStatusList = [
    "我发布的",
    "我卖出的",
    "我买到的",
  ];
  final List<String> _consignStatusImageList = [
    "assets/images/mine/grouping.png",
    "assets/images/mine/toBePayed.png",
    "assets/images/mine/toBeSent.png",
  ];

  @override
  void initState() {
    super.initState();
    registerEvents();
    reloadData();
  }

  reloadData() async {
    if (mounted) {
      EcyUserModel? user = await EcyUserUtil.getLoginedUserInfo();
      if (user != null) {
        setState(() {
          _user = user;
          if (_user.token.isNotEmpty) {
            _initHasNewMessage();
            _initUserLevel();
          }
        });
      } else {
        setState(() {
          _user = EcyUserModel("");
        });
      }
    }
  }

  reloadOrderData() async {
    if (mounted) {
      var loginFlag = await EcyUserUtil.logined();
      if (!loginFlag) return;
      List<int> response = [];
      try {
        response = await Future.wait([
          getOrderData("2"),
          getOrderData("0"),
          getOrderData("3"),
          getOrderData("4")
        ]);
      } catch (e) {
        EcyLogger.log(e.toString());
      }
      if (response.isNotEmpty) {
        setState(() {
          _orderNumList[0] = response[0];
          _orderNumList[1] = response[1];
          _orderNumList[2] = response[2];
          _orderNumList[3] = response[3];
        });
      }
    }
  }

  Future<int> getOrderData(String orderStatus) async {
    Map<String, dynamic> body = {
      "pageSize": 1,
      "pageIndex": 1,
      "orderStatus": orderStatus
    };
    var response =
        await EcyRequestbasemanager().get("/app/api/app/user/order", body);
    if (response != null) {
      var myOrderRespModel =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (myOrderRespModel.code == 0 || myOrderRespModel.code == 200) {
        EcyApiCommonPage<EcyMyOrder> commonPage = EcyApiCommonPage.fromJson(
            response["data"], (json) => EcyMyOrder.fromJson(json));
        return commonPage.total ?? 0;
      } else {
        return 0;
      }
    }
    return 0;
  }

  Future<void> _initHasNewMessage() async {
    var response =
        await EcyRequestbasemanager().get(EcyAPI.unreadCount.url, {});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        setState(() {
          _unreadCount = (response["data"] ?? 0) as int;
        });
      }
    }
  }

  Future<void> _initUserLevel() async {
    var response =
        await EcyRequestbasemanager().get(EcyAPI.appUserInfo.url, {});
    if (response != null) {
      var commonResponse =
          EcyApiCommonResponse.fromJson(response, (response) => json);
      if (commonResponse.code == 0 || commonResponse.code == 200) {
        if (response['data'] != null) {
          setState(() {
            _userLevel = (response['data']["userLevel"] ?? -1) as int;
          });
        }
      }
    }
  }

  //头像
  Widget avatar = Image.asset('assets/images/profile.png',
      width: 72, height: 72, fit: BoxFit.fitHeight);
  Widget rightArrow = Image.asset(
    'assets/images/Vector.png',
    width: 5.74,
    height: 10.31,
  );

  Widget isVip() {
    if (_userLevel == 0) {
      return Image.asset(
        'assets/images/svip@2x.png',
        width: 75.w,
        height: 88.w,
        fit: BoxFit.cover,
      );
    } else if (_userLevel == 1) {
      return Image.asset(
        'assets/images/vip@2x.png',
        width: 75.w,
        height: 88.w,
        fit: BoxFit.cover,
      );
    } else {
      return Container();
    }
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
        physics: const AlwaysScrollableScrollPhysics(),
        child: Container(
          decoration: const BoxDecoration(color: Color(0xFFF5F5F5)),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                width: double.infinity,
                height: 300.h,
                child: Stack(children: [
                  Positioned(
                      top: 0.h,
                      left: 0,
                      child: SizedBox(
                          width: MediaQuery.of(context).size.width,
                          height: 250.h,
                          child: Container(
                            decoration: const BoxDecoration(
                              gradient: LinearGradient(colors: [
                                Color(0xFFD7E8FC),
                                Color(0xFFFFDFEF)
                              ]),
                            ),
                          ))),
                  Positioned(
                      top: 45.h,
                      right: 5,
                      child: SizedBox(
                          width: 50.w,
                          height: 50.w,
                          child: IconButton(
                              onPressed: () async {
                                EcyRouter.pushWithNeedLogin(
                                    context,
                                    EcyRouter.mySettingPage,
                                    {EcyRouter.kTargetUrl: ''});
                              },
                              icon: Image.asset(
                                'assets/images/mine/setting.png',
                                width: 25,
                                height: 25,
                              )))),
                  if (_userLevel != 1 && _userLevel != 0)
                    Positioned(
                        top: 88.h,
                        left: 23,
                        child: ClipOval(
                            child: CachedNetworkImage(
                          width: 72.w,
                          height: 72.w,
                          imageUrl: _user?.avatar ?? "",
                          imageBuilder: (context, imageProvider) => Container(
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(35.r)),
                                image: DecorationImage(
                                  image: imageProvider,
                                  fit: BoxFit.cover,
                                )),
                          ),
                          placeholder: (context, url) => avatar,
                          errorWidget: (context, url, error) => avatar,
                        ))),
                  if (_userLevel == 1 || _userLevel == 0)
                    Positioned(
                      top: 75.h,
                      left: 23,
                      child: Stack(
                        children: [
                          Positioned(
                              top: 13.w,
                              left: 1.w,
                              child: ClipOval(
                                  child: CachedNetworkImage(
                                width: 72.w,
                                height: 72.w,
                                imageUrl: _user?.avatar ?? "",
                                imageBuilder: (context, imageProvider) =>
                                    Container(
                                  decoration: BoxDecoration(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(35.r)),
                                      image: DecorationImage(
                                        image: imageProvider,
                                        fit: BoxFit.cover,
                                      )),
                                ),
                                placeholder: (context, url) => avatar,
                                errorWidget: (context, url, error) => avatar,
                              ))),
                          isVip(),
                        ],
                      ),
                    ),
                  Positioned(
                      top: 88.h,
                      child: SizedBox(
                        height: 100.h,
                        width: MediaQuery.of(context).size.width,
                        child: ListTile(
                          contentPadding:
                              const EdgeInsets.only(left: 115, right: 20),
                          title: Transform(
                            transform: Matrix4.translationValues(-10, -3, 0.0),
                            child: _userLevel == 0 || _userLevel == 1
                                ? ShaderMask(
                                    shaderCallback: (bounds) {
                                      return const LinearGradient(
                                        begin: Alignment.centerLeft,
                                        end: Alignment.centerRight,
                                        colors: <Color>[
                                          Color(0xFF88B0FF),
                                          Color(0xFFFFAEB2),
                                          Color(0xFFFF96C1)
                                        ],
                                      ).createShader(Rect.fromLTWH(
                                          0, 0, bounds.width, bounds.height));
                                    },
                                    blendMode: BlendMode.srcIn, // 只应用渐变到文字
                                    child: Text(
                                      (_user != null && _user!.token.isNotEmpty
                                          ? (_user?.nickname ??
                                              _user?.username ??
                                              "")
                                          : "注册/登录"),
                                      style: TextStyle(
                                        fontWeight: FontWeight.w900,
                                        fontSize: 18.sp,
                                      ),
                                    ),
                                  )
                                : Text(
                                    (_user != null && _user!.token.isNotEmpty
                                        ? (_user?.nickname ??
                                            _user?.username ??
                                            "")
                                        : "注册/登录"),
                                    style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w900,
                                      fontSize: 18.sp,
                                      color:
                                          const Color(0xFF262626), // 普通用户显示黑色
                                    ),
                                  ),
                          ),
                          subtitle: Transform(
                              transform: Matrix4.translationValues(-9, 3, 0.0),
                              child: Text(
                                (_user != null && _user!.token.isNotEmpty
                                    ? _user!.signature ?? '来都来了介绍一下自己吧～'
                                    : '点击注册登录'),
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF595959)),
                                maxLines: 2,
                                overflow: TextOverflow.ellipsis,
                              )),
                          trailing: ClipOval(
                              child: Container(
                                  color:
                                      const Color(0xFF000000).withOpacity(0.13),
                                  width: 20,
                                  height: 20,
                                  child: Padding(
                                      padding: const EdgeInsets.symmetric(
                                        vertical: 5,
                                      ),
                                      child: rightArrow))),
                          onTap: () async {
                            EcyRouter.pushWithNeedLogin(
                                context,
                                EcyRouter.personInfoPage,
                                {EcyRouter.kTargetUrl: ''});
                          },
                        ),
                      )),
                  Positioned(
                      top: 180.h,
                      left: 8,
                      child: SizedBox(
                        width: MediaQuery.of(context).size.width - 16,
                        height: 120.h,
                        child: Container(
                          decoration: const BoxDecoration(
                              color: Colors.white,
                              borderRadius:
                                  BorderRadius.all(Radius.circular(10))),
                        ),
                      )),
                  Positioned(
                      top: 200.h,
                      left: 28,
                      child: Text(
                        '我的订单',
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFF262626)),
                      )),
                  Positioned(
                    top: 200.h,
                    right: 28,
                    child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: () {
                          handleOrderTap(context, 0);
                        },
                        child: Row(
                          children: [
                            Text('全部',
                                style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontWeight: FontWeight.w500,
                                    fontSize: 14.sp,
                                    color: const Color(0xFF8C8C8C))),
                            const Image(
                                image:
                                    AssetImage('assets/images/rightArrow.png'),
                                width: 12)
                          ],
                        )),
                  ),
                  Positioned(
                      top: 225.h,
                      left: 8,
                      child: SizedBox(
                        width: MediaQuery.of(context).size.width - 16,
                        child: Row(
                          children: _orderStatusList.map((n) {
                            var index = _orderStatusList.indexOf(n);
                            var num = _orderNumList[index];
                            return Expanded(
                              child: GestureDetector(
                                  behavior: HitTestBehavior.opaque,
                                  onTap: () {
                                    handleOrderTap(context, index + 1);
                                  },
                                  child: Column(
                                    children: [
                                      Stack(
                                        alignment: Alignment.topRight,
                                        children: [
                                          Padding(
                                            padding:
                                                const EdgeInsets.only(top: 8),
                                            child: Image(
                                                image: AssetImage(
                                                    _orderStatusImageList[
                                                        index]),
                                                width: 32.w),
                                          ),
                                          if (num > 0)
                                            Positioned(
                                              right: 0,
                                              top: 5,
                                              child: Container(
                                                width: 12.w,
                                                height: 12.w,
                                                padding:
                                                    const EdgeInsets.all(1),
                                                decoration: const BoxDecoration(
                                                  color: Colors.red,
                                                  shape: BoxShape
                                                      .circle, // 圆形角标（可选rectangle矩形）
                                                ),
                                                child: Text(
                                                  '${num > 99 ? '99' : num}',
                                                  style: TextStyle(
                                                      fontFamily: "PingFag SC",
                                                      fontWeight:
                                                          FontWeight.w400,
                                                      fontSize: 8.sp,
                                                      color: Colors.white),
                                                  textAlign: TextAlign.center,
                                                ),
                                              ),
                                            )
                                        ],
                                      ),
                                      Text(n,
                                          style: TextStyle(
                                              fontFamily: "PingFang SC",
                                              fontWeight: FontWeight.w500,
                                              fontSize: 14.sp,
                                              color: const Color(0xFF262626))),
                                    ],
                                  )),
                            );
                          }).toList(),
                        ),
                      )),
                ]),
              ),
              const Padding(padding: EdgeInsets.only(bottom: 8)),
              // ...在“我的寄售”Widget下方插入
              Padding(
                padding: EdgeInsets.all(8.w),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          // 跳转到“我的痛柜”页面
                          EcyRouter.pushWithNeedLogin(context, EcyRouter.blindBoxMyAssets, {EcyRouter.kTargetUrl: EcyRouter.blindBoxMyAssets});
                        },
                        child: Container(
                          height: 60.h,
                          margin: EdgeInsets.only(right: 8.w),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Center(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                Image.asset(
                                  'assets/images/my_cabinet.png',
                                  width: 24,
                                  height: 24,
                                ),
                                SizedBox(width: 50.w),
                               Text(
                               "我的痛柜",
                               style: TextStyle(
                                  fontFamily: "PingFang SC",
                                  fontWeight: FontWeight.w700,
                                  fontSize: 16.sp,
                                  color: const Color(0xFF262626)),
                              ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      child: GestureDetector(
                        onTap: () {
                          // 跳转到“我的交换”页面
                          EcyRouter.pushWithNeedLogin(context, EcyRouter.blindBoxMyexchange, {EcyRouter.kTargetUrl: EcyRouter.blindBoxMyexchange});
                        },
                        child: Container(
                          height: 60.h,
                          margin: EdgeInsets.only(left: 8.w),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(12.r),
                          ),
                          child: Center(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                               Image.asset(
                                'assets/images/my_exchange.png',
                                 width: 24,
                                 height: 24,
                                ),
                                SizedBox(width: 50.w),
                              Text(
                               "我的交换",
                               style: TextStyle(
                               fontFamily: "PingFang SC",
                               fontWeight: FontWeight.w700,
                               fontSize: 16.sp,
                               color: const Color(0xFF262626)),
                               ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Card(
                color: Colors.white,
                elevation: 0,
                margin: const EdgeInsets.symmetric(horizontal: 8),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Padding(
                      padding: const EdgeInsets.fromLTRB(20, 15, 20, 15),
                      child: Text(
                        "我的寄售",
                        style: TextStyle(
                            fontFamily: "PingFang SC",
                            fontWeight: FontWeight.w700,
                            fontSize: 16.sp,
                            color: const Color(0xFF262626)),
                      ),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: _consignStatusList.map((n) {
                        var index = _consignStatusList.indexOf(n);
                        return Expanded(
                          flex: 1,
                          child: GestureDetector(
                            behavior: HitTestBehavior.opaque,
                            onTap: () {
                              handleConsignmentTap(context, index);
                            },
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.center,
                              children: [
                                Image(
                                    image: AssetImage(
                                        _consignStatusImageList[index]),
                                    width: 32.w),
                                const Padding(
                                    padding: EdgeInsets.only(bottom: 5)),
                                Text(n,
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF262626)))
                              ],
                            ),
                          ),
                        );
                      }).toList(),
                    ),
                    const Padding(padding: EdgeInsets.only(bottom: 15)),
                  ],
                ),
              ),
              const Padding(padding: EdgeInsets.only(bottom: 8)),
              // const Padding(padding: EdgeInsets.only(bottom: 8)),
              Container(
                  padding: const EdgeInsets.only(top: 0),
                  width: MediaQuery.of(context).size.width - 16,
                  child: ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    padding: EdgeInsets.zero,
                    itemCount: titleList.length,
                    itemBuilder: (context, index) {
                      return Card(
                        color: Colors.white,
                        margin: const EdgeInsets.only(bottom: 2),
                        elevation: 0,
                        child: ListTile(
                          title: Text(
                            titleList[index],
                            style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontWeight: FontWeight.w700,
                                fontSize: 16.sp,
                                color: const Color(0xFF262626)),
                          ),
                          trailing: RichText(
                            text: TextSpan(
                              children: [
                                if (index == 2 && _unreadCount > 0)
                                  WidgetSpan(
                                    child: Container(
                                      width: 13.w,
                                      height: 13.w,
                                      padding: const EdgeInsets.all(1),
                                      decoration: const BoxDecoration(
                                        color: Colors.red,
                                        shape: BoxShape.circle, // 圆形角标
                                      ),
                                      child: Text(
                                        '${_unreadCount > 99 ? '99' : _unreadCount}',
                                        style: TextStyle(
                                            fontFamily: "PingFag SC",
                                            fontWeight: FontWeight.w400,
                                            fontSize: 8.sp,
                                            color: Colors.white),
                                        textAlign: TextAlign.center,
                                      ),
                                    ),
                                  ),
                                const WidgetSpan(
                                  child: Icon(
                                    Icons.arrow_forward_ios,
                                    size: 13,
                                  ),
                                ),
                              ],
                            ),
                          ),
                          splashColor: Colors.transparent,
                          onTap: () {
                            EcyRouter.pushWithNeedLogin(
                                context,
                                routeMap[index]!,
                                {EcyRouter.kTargetUrl: routeMap[index]!});
                          },
                        ),
                      );
                    },
                  ))
            ],
          ),
        ));
  }

  @override
  void dispose() {
    super.dispose();
    // disposeEvents();
  }

  @override
  void deactivate() {
    reloadData();
    super.deactivate();
  }

  void registerEvents() {
    EcyEventBus().on(EcyEventConst.kLogined, (arg) {
      reloadData();
      reloadOrderData();
    });
    EcyEventBus().on(EcyEventConst.kEditUser, (arg) {
      reloadData();
    });
    EcyEventBus().on(EcyEventConst.kMessagesRead, (arg) {
      _initHasNewMessage();
    });
    EcyEventBus().on(EcyEventConst.kOnOrder, (arg) {
      reloadOrderData();
    });
  }

  void disposeEvents() {
    EcyEventBus().off(EcyEventConst.kLogined);
    EcyEventBus().off(EcyEventConst.kEditUser);
    EcyEventBus().off(EcyEventConst.kMessagesRead);
  }
}
